package com.efounder.push;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.Application;
import android.content.Context;
import android.os.Process;
import androidx.annotation.NonNull;
import android.util.Log;

import com.efounder.constant.EnvironmentVariable;
import com.efounder.util.MobilePushUtils;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.FirebaseApp;
import com.google.firebase.iid.FirebaseInstanceId;
import com.google.firebase.iid.InstanceIdResult;
import com.huawei.android.hms.agent.HMSAgent;
import com.huawei.android.hms.agent.common.handler.ConnectHandler;
import com.huawei.android.hms.agent.push.handler.GetTokenHandler;
import com.utilcode.util.LogUtils;
import com.utilcode.util.ReflectUtils;
import com.xiaomi.channel.commonutils.logger.LoggerInterface;
import com.xiaomi.mipush.sdk.Logger;
import com.xiaomi.mipush.sdk.MiPushClient;

import org.greenrobot.eventbus.EventBus;

import java.util.List;

/**
 * 手机push初始化
 */
public class PushManager {

    private static final String TAG = "PushManager";
    private Context mContext;

    public PushManager(Context mContext) {
        this.mContext = mContext;
    }

    /**
     * 初始化push（BaseApp中调用）
     */
    public void initPush() {
        //ToastUtil.showToast(mContext, "initPush");
        if (MobilePushUtils.isSupportPush() && MobilePushUtils.isSupportHuaWeiPush()) {
            initHuaWeiPush();
            return;
        }
        if (MobilePushUtils.isSupportPush() && MobilePushUtils.isSupportXiaoMiPush()) {
            initXiaoMiPush();
            return;
        }

        if (MobilePushUtils.isSupportPush() && MobilePushUtils.isSupportGoogleService(mContext)) {
            initFCM();
        }
    }

    /**
     * 初始化google firebase cloud message 推送
     */
    private void initFCM() {
        FirebaseApp.initializeApp(mContext);
    }

    /**
     * 初始化华为push
     */
    public void initHuaWeiPush() {
        HMSAgent.init((Application) mContext);
    }

    /**
     * 初始化小米push
     */
    public void initXiaoMiPush() {
        // LogUtils.i("initXiaoMiPush");
        //初始化push推送服务
        if (shouldInit()) {
            String xiaoMiPushAppId = EnvironmentVariable.getProperty("xiaoMiPushAppId");
            String xiaoMiPushAppKey = EnvironmentVariable.getProperty("xiaoMiPushAppKey");
            MiPushClient.registerPush(mContext, xiaoMiPushAppId, xiaoMiPushAppKey);
        }
        //打开Log
        LoggerInterface newLogger = new LoggerInterface() {

            @Override
            public void setTag(String tag) {
                // ignore
            }

            @Override
            public void log(String content, Throwable t) {
                Log.d(TAG, content, t);
            }

            @Override
            public void log(String content) {
                Log.d(TAG, content);
            }
        };
        Logger.setLogger(mContext, newLogger);
    }


    /**
     * 获取push 推送服务的token（这是在activity中调用）
     */
    public void initPushTokenAndConnect() {
        // ToastUtil.showToast(mContext,"initPushTokenAndConnect");
        //华为push 需要在activity中进行连接 获取token
        if (MobilePushUtils.isSupportPush() && MobilePushUtils.isSupportHuaWeiPush()) {
            connectHWS();
            getHuaWeiPushToken();
        }
    }

    /**
     * 连接华为push
     */
    private void connectHWS() {
        //华为push初始化Agent
        // 在首个界面，需要调用connect进行连接 | In the first page, you need to call connect
        HMSAgent.connect((Activity) mContext, new ConnectHandler() {
            @Override
            public void onConnect(int rst) {
                LogUtils.i("HMS connect end:", "" + rst);
            }
        });

    }

    /**
     * 获取华为push的token
     */
    private void getHuaWeiPushToken() {
        if (!"".equals(EnvironmentVariable.getProperty("pushToken", ""))) {
            EnvironmentVariable.setProperty("lastPushToken", EnvironmentVariable.getProperty("pushToken", ""));
        }
        ///EnvironmentVariable.setProperty("pushToken", "");
        HMSAgent.Push.getToken(new GetTokenHandler() {
            @Override
            public void onResult(int rtnCode) {
                LogUtils.i("get token end code=", rtnCode + "");
            }
        });
    }


    /**
     * 获取google Firebase Cloud Messaging推送Token
     */
    private void getFCMPushToken() {
        if (MobilePushUtils.isSupportPush() && MobilePushUtils.isSupportGoogleService(mContext)) {
            if (!"".equals(EnvironmentVariable.getProperty("pushToken", ""))) {
                EnvironmentVariable.setProperty("lastpushToken", EnvironmentVariable.getProperty("pushToken", ""));
            }
            try {
                FirebaseInstanceId.getInstance().getInstanceId()
                        .addOnCompleteListener(new OnCompleteListener<InstanceIdResult>() {
                            @Override
                            public void onComplete(@NonNull Task<InstanceIdResult> task) {
                                if (!task.isSuccessful()) {
                                    Log.w(TAG, "getInstanceId failed", task.getException());
                                    return;
                                }
                                // Get new Instance ID token
                                String token = task.getResult().getToken();
                                EnvironmentVariable.setProperty("pushToken", token);
                                // Log and toast
                                Log.d(TAG, token);
                                try {
                                    //Class className = Class.forName("com.efounder.chat.event.PushTokenEvent");
                                    Object object = ReflectUtils.reflect("com.efounder.chat.event.PushTokenEvent").newInstance(token).get();
                                    EventBus.getDefault().post(object);
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            }
                        });
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 小米推送的方法(为了只在主进程初始化小米push)
     *
     * @return
     */
    private boolean shouldInit() {
        ActivityManager am = ((ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE));
        List<ActivityManager.RunningAppProcessInfo> processInfos = am.getRunningAppProcesses();
        String mainProcessName = mContext.getPackageName();
        int myPid = Process.myPid();
        for (ActivityManager.RunningAppProcessInfo info : processInfos) {
            if (info.pid == myPid && mainProcessName.equals(info.processName)) {
                return true;
            }
        }
        return false;
    }


    /**
     * 清理所有的push通知栏消息(小米sdk支持)
     */
    public void clearPushNotification() {
        // MiPushClient.clearNotification(mContext, notifyId);
        MiPushClient.clearNotification(mContext);
    }
}
